package leetcode.D100.T77;

import java.util.ArrayList;
import java.util.List;

class Solution {
    // 一刷
    /*public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new LinkedList<>();
        Deque<Integer> stack = new LinkedList<>();
        dfs(result, stack, 0, n, k, 0);
        return result;
    }
    private void dfs(List<List<Integer>> result, Deque<Integer> stack, int depth, int n, int k, int last) {
        if(n - last < k - depth) {
            return;
        }
        if(depth == k) {
            result.add(new ArrayList<>(stack));
            return;
        }
        for(int i=last+1; i<=n; ++i) {
            stack.addLast(i);
            dfs(result, stack, depth+1, n, k, i);
            stack.removeLast();

        }
    }*/

    // 二刷
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(results, path, n, k, 0);
        return results;
    }

    private void dfs(List<List<Integer>> results, List<Integer> path, int n, int k, int cur) {
        if (path.size() == k) {
            results.add(new ArrayList<>(path));
            return;
        }
        for(int i=cur+1; i<=n-k+path.size()+1; ++i) {
            path.add(i);
            dfs(results, path, n, k, i);
            path.remove(path.size()-1);
        }
    }
}
